package api.storage;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import api.Person;

/**
 * @author Ann Raboschuk
 *
 */
public class DataStorageCSV implements IDataStorage
{
   private String filename;
   
   public DataStorageCSV(String filename)
   {
      this.filename = filename;
   }
   
   /**
    * Method writes list of objects to specified TXT file.
    * 
    * @param list - list to be written to file
    * @throws IOException
    */
   @Override
   public void save(List<Person> list) throws IOException 
   {
      BufferedWriter outputFile = new BufferedWriter(new FileWriter(filename));
      Iterator<Person> iterator = list.iterator();
      Person current;
      while (iterator.hasNext())
      {
         current = iterator.next();
         outputFile.write(current.toString() + "\r\n");
      }
      outputFile.close();
   }

   /**
    * Method retrieves stored list from TXT file.
    * 
    * @return list - list of read objects
    * @throws IOException
    */
   @Override
   public List<Person> load() throws IOException
   {
      List<Person> list = new ArrayList<Person>();
      BufferedReader inputFile = new BufferedReader(new FileReader(filename));
      String line;      
      try
      {
         while ((line = inputFile.readLine()) != null)
         {
            list.add(list.size(), Person.fromString(line));
         }
      }
      catch (Exception ex)
      {
         ex.printStackTrace();
      }
      inputFile.close();
      return list;
   }
}
